package com.bzg.manager.service.impl;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.bzg.manager.bean.FridendsDetail;
import com.bzg.manager.bean.Friends;
import com.bzg.manager.bean.User;
import com.bzg.manager.controller.UserController;
import com.bzg.manager.dao.UserMapper;
import com.bzg.manager.easymob.model.TalkNode;
import com.bzg.manager.easymob.service.impl.TalkDataServiceImpl;
import com.bzg.manager.easymob.service.impl.TalkHttpServiceImplApache;
import com.bzg.manager.exception.BaseExceptionTool;
import com.bzg.manager.param.LoginParam;
import com.bzg.manager.param.ReturnParam;
import com.bzg.manager.param.UserParam;
import com.bzg.manager.service.UserService;
import com.bzg.manager.utils.MD5;
import com.bzg.manager.utils.PasswordEnc;

@Service
public class UserServiceImpl implements UserService {
	
	public static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Autowired
	private UserMapper userMapper;
	
	@Value("${imgBasePath}")
	private String IMGBASEPATH;
	
	@Override
	public User login(LoginParam param) {
		//加密密码
		param.setPassword(PasswordEnc.encPassword(param.getPassword()));
		param.setUserName(param.getUserName().toUpperCase());
		
		User user = userMapper.login(param);
		if(user == null){
			throw BaseExceptionTool.LOGIN_FAIL;
		}
		//登录成功后判断是否已经注册环信
		if(StringUtils.isEmpty(user.getEasymob_name()) || StringUtils.isEmpty(user.getEasymob_pwd())){
			//用户没有注册环信用户，需注册
			TalkHttpServiceImplApache talkHttpService = new TalkHttpServiceImplApache();
			TalkDataServiceImpl talkDataService = new TalkDataServiceImpl(talkHttpService);
			try {
				TalkNode talkNode = talkDataService.register(user.getUserName(), MD5.md5(user.getPassword()));
				if(talkNode != null && talkNode.getStatusCode()== null){
					//注册环信成功
					log.info("用户：" + user.getUserName() + "注册环信成功！");
					//将环信用户名密码写入数据库
					user.setEasymob_name(user.getUserName());
					user.setEasymob_pwd(MD5.md5(user.getPassword()));
					userMapper.updateEasymob(user);
				}else{
					log.error("用户：" + user.getUserName() + "注册环信失败！");
				}
			} catch (Exception e) {
				log.error("用户：" + user.getUserName() + "注册环信失败！");
			}
			
		}
		//登录成功则生成token，记录登录时间和push_id;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String token = MD5.md5(param.getUserName() + param.getPassword() + format.format(new Date()));
		
		user.setToken(token);
		user.setPushId(param.getPush_id());
		
		//写入表中
		userMapper.updateUser(user);
		
		User reUser = new User();
		reUser.setUserName(user.getUserName());
		reUser.setPassword(user.getPassword());
		reUser.setToken(user.getToken());
		reUser.setVendCode(user.getVendCode());
		reUser.setVendName(user.getVendName());
		if(StringUtils.isNotEmpty(user.getImgPath())){
			reUser.setImgPath(IMGBASEPATH + user.getImgPath());
		}else{
			reUser.setImgPath(user.getImgPath());
		}
		reUser.setEasymob_name(user.getEasymob_name());
		reUser.setEasymob_pwd(user.getEasymob_pwd());
		reUser.setLocalName(user.getLocalName());
		return reUser;
	}

	@Override
	public String changePassword(UserParam userParam) {
		if(userParam == null || StringUtils.isEmpty(userParam.getNewPassword()) 
				|| StringUtils.isEmpty(userParam.getOldPassword())
				|| StringUtils.isEmpty(userParam.getNewPassword())
				|| StringUtils.isEmpty(userParam.getUserName())){
			throw BaseExceptionTool.PARAM_IS_NULL;
			}
		//校验完参数之后，加密密码
		userParam.setOldPassword(PasswordEnc.encPassword(userParam.getOldPassword()));
		userParam.setNewPassword(PasswordEnc.encPassword(userParam.getNewPassword()));
		userParam.setUserName(userParam.getUserName().toUpperCase());
		//更新密码
		int updateFlag = userMapper.updatePassword(userParam);
		if(updateFlag != 1){
			throw BaseExceptionTool.CHANGE_PWD_FAIL;
		}
		//删除token 取消登录状态
		int delFalg = userMapper.deleteToken(userParam);
		if(delFalg != 1){
			throw BaseExceptionTool.CHANGE_PWD_FAIL;
		}
		//修改成功
		return "Y";
	}

	@Override
	public void logout(UserParam userParam) {
		if(userParam == null || StringUtils.isEmpty(userParam.getUserName())){
			throw BaseExceptionTool.PARAM_IS_NULL;
		}
		/**
		 * 退出登录，设置token为空
		 */
		userMapper.deleteToken(userParam);
	}

	@Override
	public String feedback(UserParam userParam) {
		if(userParam == null || StringUtils.isEmpty(userParam.getUserName())){
			throw BaseExceptionTool.PARAM_IS_NULL;
		}
		try {
			if(userParam.getContent().getBytes("UTF-8").length > 200){
				throw BaseExceptionTool.LENGTH_TOO_LONG;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		/**
		 * insert反馈信息
		 */
		int insertFeedback = userMapper.insertFeedback(userParam);
		if(insertFeedback == 1){
			return "Y";
		}
		
		return "N";
	}

	@Override
	public String saveImgPath(UserParam userParam) {
		if(userParam == null || StringUtils.isEmpty(userParam.getImgName())){
			throw BaseExceptionTool.PARAM_IS_NULL;
		}
		userParam.setUserName(userParam.getUserName().toUpperCase());
		int flag = userMapper.saveImgPath(userParam);
		if(flag != 1){
			log.error("==========保存" + userParam.getUserName() + "图片路径出错===========");
			throw BaseExceptionTool.DB_ERROR;
		}
		return "Y";
	}

	@Override
	public String getUserImgName(String userName) {
		return userMapper.getImgName(userName);
	}

	@Override
	public Boolean checkToken(String token) {
		if(StringUtils.isEmpty(token)){
			return false;
		}
		Integer count = userMapper.checkToken(token);
		if(count == 1){
			return true;
		}
		return false;
	}

	@Override
	public List<User> getFriendsList(UserParam param) {
		if(param == null || StringUtils.isEmpty(param.getVendCode())){
			throw BaseExceptionTool.PARAM_IS_NULL;
		}
		param.setVendCode(param.getVendCode().toUpperCase());
		List<User> list = userMapper.getFriendsList(param);
		if(list != null && list.size() > 0){
			for (User user : list) {
				//将vendCode 转为 currentVendCode
				user.setCurrentVendCode(user.getVendCode());
				user.setVendCode(null);
				if(StringUtils.isNotEmpty(user.getImgPath())){//如果头像地址不为空则加上前缀
					user.setImgPath(IMGBASEPATH + user.getImgPath());
				}
			}
		}
		return list;
	}

	@Override
	public User getFriendInfo(UserParam param) {
		if(param == null || StringUtils.isEmpty(param.getEasymob_name())){
			throw BaseExceptionTool.PARAM_IS_NULL;
		}
		param.setEasymob_name(param.getEasymob_name().toUpperCase());
		User user = userMapper.getFriendInfo(param);
		if(user != null){
			//将vendCode 转为 currentVendCode
			user.setCurrentVendCode(user.getVendCode());
			user.setVendCode(null);
			if(StringUtils.isNotEmpty(user.getImgPath())){//如果头像地址不为空则加上前缀
				user.setImgPath(IMGBASEPATH + user.getImgPath());
			}
		}
		return user;
	}

	@Override
	public List<Friends> getFriends(UserParam param) {
		List<Friends> list = userMapper.getFriends(param);
		if(list != null && list.size() > 0){
			for (int i = 0; i < list.size(); i++) {
				Friends friends = list.get(i);
				if(friends != null){
					List<FridendsDetail> fdList = friends.getFriendsList();
					if(fdList != null && fdList.size() > 0){
						for (int j = 0; j < fdList.size(); j++) {
							FridendsDetail fd = fdList.get(j);
							if(fd != null){
								if(StringUtils.isNoneBlank(fd.getImgPath())){
									fd.setImgPath(IMGBASEPATH + fd.getImgPath());
								}
							}
						}
					}
					
				}
			}
		}
		return list;
	}

	@Override
	public String batchRegistrat() {
		//首先获取未注册环信的所有用户
		List<User> users = userMapper.getUnregisteredUsers();
		if(users == null || users.size() == 0){
			throw BaseExceptionTool.NO_REGISTRATION;
		}
		//调用批量注册的方法
		TalkHttpServiceImplApache talkHttpService = new TalkHttpServiceImplApache();
		TalkDataServiceImpl talkDataService = new TalkDataServiceImpl(talkHttpService);
		//遍历list注册用户
		int count = 0;
		for (int i = 0; i < users.size(); i++) {
			
			try {
				TalkNode talkNode = talkDataService.register(users.get(i).getUserName(), MD5.md5(users.get(i).getPassword()));
				if(talkNode != null &&talkNode.getStatusCode() != null && talkNode.getStatusCode() != 200){
					log.error("============用户：" + users.get(i).getUserName() + "注册环信失败！！！===============");
					continue;
				}
				if(talkNode == null){
					log.error("============用户：" + users.get(i).getUserName() + "注册环信失败！！！===============");
					continue;
				}
				//注册成功后将环信用户名存进数据库
				users.get(i).setEasymob_name(users.get(i).getUserName());
				users.get(i).setEasymob_pwd(MD5.md5(users.get(i).getPassword()));
				userMapper.updateEasymob(users.get(i));
				count++;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String msg = "实际需注册用户数为：" + users.size() + ",成功注册用户数量为：" + count + "";
		return msg;
	}
		

}
